package org.abratuhi.kvngroupware.network;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;


public class C_Client extends AbstractClient{
	
	String host;
	Integer port;
	

	public C_Client(Socket socket, MessageProceeder mproceeder){
		super(socket, mproceeder);
	}
	
	public C_Client(String host, Integer port, MessageProceeder mproceeder){
		super(null, mproceeder);
		this.host = host;
		this.port = port;
	}
	
	public void sendString(String str){
		super.sendString(str);
		System.out.println("C_CLIENT [send]: "+str); //TODO: logger
	}
	
	public String receiveString(){
		String str = super.receiveString();
		System.out.println("C_CLIENT [recv]: "+str); // TODO: logger
		return str;
	}
	
	public void run(){
		while(getRunOK()){
			try {
				Message message = receiveMessage();
				if(message!=null) mproceeder.proceedMessage(this, message);
				Thread.sleep(100);
			} catch (InterruptedException e) {
				System.out.println("C_CLIENT [interrupt]"); // TODO: logger
				break;
			}
		}
		return;
	}
	
	public void start(){
		this.connect();
		super.start();
		System.out.println("C_CLIENT [start]"); // TODO: logger
	}
	
	public void stop(){
		super.stop();
		this.disconnect();
		System.out.println("C_CLIENT [stop]"); // TODO: logger
	}
	
	public void connect(){
		try {
			socket = new Socket(host, port);
			System.out.println("C_CLIENT [connect]"); // TODO: logger
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void disconnect(){
		try {
			socket.close();
			System.out.println("C_CLIENT [disconnect]"); // TODO: logger
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void doOnCommunicationError() {
		stop();
	}

}
